<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="(val) => $emit('update:visible', val)"
    :title="'报告详情 - ' + (report?.test_case?.name || '未知')"
    width="80%"
    top="5vh"
    @close="onClose"
    destroy-on-close
  >
    <div v-if="report" class="report-detail">
      <!-- 基础信息 -->
      <el-descriptions :column="2" border size="small" class="mb-4">
        <el-descriptions-item label="状态">
          <el-tag :type="statusType">{{ statusText }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="耗时"
          >{{ report.duration.toFixed(3) }} 秒</el-descriptions-item
        >
        <el-descriptions-item label="执行时间">
          {{ new Date(report.executed_at).toLocaleString() }}
        </el-descriptions-item>
        <el-descriptions-item label="类型">
          <el-tag v-if="isPerformanceTest" type="warning">性能压测</el-tag>
          <el-tag v-else type="success">接口执行</el-tag>
        </el-descriptions-item>
      </el-descriptions>

      <!-- 性能压测指标 -->
      <div v-if="isPerformanceTest" class="perf-section">
        <h4>📈 性能指标</h4>
        <el-table
          :data="[report.performance_metrics]"
          size="small"
          style="width: 100%"
          :show-header="false"
        >
          <el-table-column>
            <template #default="{ row }">
              <div v-for="(value, key) in row" :key="key" class="metric-row">
                <strong>{{ formatLabel(key) }}</strong>
                <span>{{ formatValue(key, value) }}</span>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 普通执行结果 -->
      <div v-else class="normal-response">
        <h4>💡 执行结果</h4>

        <!-- 实际响应 -->
        <div class="response-block">
          <h5>实际响应：</h5>
          <pre class="json-pre">{{ JSON.stringify(report.actual_response, null, 2) }}</pre>
        </div>

        <!-- 断言结果 -->
        <div class="assertions-block mt-3">
          <h5>断言结果：</h5>
          <el-table :data="report.assertion_results" size="small" border>
            <el-table-column prop="check" label="检查项" />
            <el-table-column prop="expected" label="期望值" />
            <el-table-column prop="actual" label="实际值" />
            <el-table-column label="结果" width="80">
              <template #default="{ row }">
                <el-tag :type="row.pass ? 'success' : 'danger'" size="small">
                  {{ row.pass ? '通过' : '失败' }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { computed } from 'vue'

// 接收属性
const props = defineProps({
  report: {
    type: Object,
    required: true,
  },
  visible: {
    type: Boolean,
    required: true,
  },
})

// 触发更新
const emit = defineEmits(['update:visible', 'close'])
const onClose = () => {
  emit('close')
}

// 是否为性能压测
const isPerformanceTest = computed(() => !!props.report.performance_metrics)

// 状态标签
const statusType = computed(() => {
  const status = props.report.status
  return status === 'PASS' ? 'success' : status === 'FAIL' ? 'warning' : 'danger'
})
const statusText = computed(() => {
  return { PASS: '通过', FAIL: '失败', ERROR: '错误' }[props.report.status] || props.report.status
})

// 字段中文映射
const labelMap = {
  // 通用
  concurrency: '并发用户数',
  duration: '持续时间(秒)',
  total_requests: '总请求数',
  successful_requests: '成功请求数',
  failed_requests: '失败请求数',
  throughput_rps: '吞吐量(RPS)',
  latency_avg_ms: '平均延迟(ms)',
  latency_min_ms: '最小延迟(ms)',
  latency_max_ms: '最大延迟(ms)',
  latency_p90_ms: 'P90延迟(ms)',
  latency_p95_ms: 'P95延迟(ms)',
  latency_p99_ms: 'P99延迟(ms)',
  error_rate: '错误率',
  success_rate: '成功率',
  status_codes: '状态码分布',
}

const formatLabel = (key) => {
  return labelMap[key] || key.replace(/_/g, ' ').replace(/\b\w/g, (l) => l.toUpperCase())
}

// 特殊值格式化
const formatValue = (key, value) => {
  if (key === 'status_codes') {
    return Object.entries(value)
      .map(([code, count]) => `${code}(${count})`)
      .join(', ')
  }
  if (typeof value === 'number') {
    return value.toFixed(3)
  }
  return String(value)
}
</script>

<style scoped>
.report-detail {
  max-height: 70vh;
  overflow-y: auto;
  font-size: 14px;
}

.metric-row {
  display: flex;
  justify-content: space-between;
  padding: 6px 0;
  border-bottom: 1px solid #f0f0f0;
  font-family: monospace;
  font-size: 13px;
}

.json-pre {
  background: #f8f9fa;
  padding: 12px;
  border-radius: 4px;
  border: 1px solid #eee;
  font-family: 'Courier New', monospace;
  font-size: 13px;
  line-height: 1.5;
  white-space: pre-wrap;
  word-wrap: break-word;
  max-height: 200px;
  overflow-y: auto;
}

.mb-4 {
  margin-bottom: 1rem;
}

.mt-3 {
  margin-top: 1rem;
}

.perf-section,
.normal-response {
  margin-bottom: 20px;
}

h4,
h5 {
  color: #333;
  margin-bottom: 12px;
}

h5 {
  font-size: 15px;
  color: #555;
}
</style>
